<template>
  <PageContainer>
    <div class="expand-page">
      <div class="expand-header">
        <h1 class="page-title">AI图片扩展</h1>
        <p class="page-description">基于原图生成相似风格的扩展图片，支持多种艺术风格和自定义配置</p>
      </div>
      
      <div class="expand-content">
        <!-- 左侧：图片选择和配置 -->
        <div class="expand-sidebar">
          <!-- 图片选择器 -->
          <ImageSelector
            :images="images"
            :loading="imagesLoading"
            :selected-image="selectedImage ?? undefined"
            @select-image="handleSelectImage"
            @load-images="handleLoadImages"
          />
          
          <!-- 扩展配置面板 -->
          <ExpansionPanel
            ref="expansionPanelRef"
            :selected-image="selectedImage ?? undefined"
            :loading="generating"
            @generate="handleGenerate"
            @regenerate="handleRegenerate"
            @use-history="handleUseHistory"
            @load-history="handleLoadHistory"
          />
        </div>
        
        <!-- 右侧：扩展结果 -->
        <div class="expand-main">
          <ExpansionResults
            :expanded-images="expandedImages"
            :original-image="selectedImage ?? undefined"
            :loading="generating"
            @preview="handlePreview"
            @download="handleDownload"
            @share="handleShare"
            @delete="handleDelete"
            @use-template="handleUseTemplate"
            @generate-more="handleGenerateMore"
            @compose="handleCompose"
            @select-best="handleSelectBest"
          />
        </div>
      </div>
      
      <!-- 图片预览对话框 -->
      <el-dialog
        v-model="previewVisible"
        title="图片预览"
        width="80%"
        :before-close="handleClosePreview"
      >
        <div class="preview-content" v-if="previewImage">
          <div class="preview-comparison">
            <!-- 原图 -->
            <div class="preview-section">
              <h3>原图</h3>
              <div class="preview-image-container">
                <img 
                  :src="selectedImage?.fileUrl" 
                  :alt="selectedImage?.originalName"
                  class="preview-image"
                />
              </div>
              <div class="preview-info">
                <p><strong>名称:</strong> {{ selectedImage?.originalName }}</p>
                <p><strong>尺寸:</strong> {{ selectedImage?.width }}×{{ selectedImage?.height }}</p>
                <p><strong>大小:</strong> {{ formatFileSize(selectedImage?.fileSize || 0) }}</p>
              </div>
            </div>
            
            <!-- 扩展图 -->
            <div class="preview-section">
              <h3>扩展图</h3>
              <div class="preview-image-container">
                <img 
                  :src="previewImage.generatedImageUrl || previewImage.tempUrl" 
                  :alt="'扩展图片'"
                  class="preview-image"
                />
              </div>
              <div class="preview-info">
                <p><strong>相似度:</strong> {{ Math.round((previewImage.similarityScore || 0) * 100) }}%</p>
                <p><strong>生成时间:</strong> {{ formatTime(previewImage.createdAt) }}</p>
                <p><strong>状态:</strong> {{ getStatusText(previewImage.aiGenerationStatus) }}</p>
                <p v-if="previewImage.generationParams">
                  <strong>风格:</strong> {{ getStyleFromParams(previewImage.generationParams) }}
                </p>
              </div>
            </div>
          </div>
          
          <div class="preview-actions">
            <el-button 
              type="primary" 
              :icon="Download"
              @click="downloadPreviewImage"
            >
              下载图片
            </el-button>
            <el-button 
              type="success" 
              :icon="DocumentAdd"
              @click="composeWithPreview"
            >
              图文组合
            </el-button>
            <el-button 
              type="info" 
              :icon="CopyDocument"
              @click="useAsTemplate"
            >
              用作模板
            </el-button>
            <el-button 
              type="warning" 
              :icon="MagicStick"
              @click="generateMoreFromPreview"
            >
              生成更多
            </el-button>
          </div>
        </div>
      </el-dialog>
      
      <!-- 批量扩展对话框 -->
      <el-dialog
        v-model="batchVisible"
        title="批量图片扩展"
        width="700px"
        :before-close="handleCloseBatch"
      >
        <div class="batch-content">
          <div class="batch-images">
            <h4>选中的图片 ({{ batchImages.length }})</h4>
            <div class="batch-images-grid">
              <div
                v-for="image in batchImages"
                :key="image.id"
                class="batch-image-item"
              >
                <img :src="image.fileUrl" :alt="image.originalName" />
                <span class="batch-image-name">{{ image.originalName }}</span>
              </div>
            </div>
          </div>
          
          <div class="batch-config">
            <h4>扩展配置</h4>
            <el-form :model="batchConfig" label-width="100px">
              <el-form-item label="生成数量">
                <el-slider
                  v-model="batchConfig.count"
                  :min="1"
                  :max="5"
                  :step="1"
                  show-stops
                  show-input
                />
              </el-form-item>
              
              <el-form-item label="扩展风格">
                <el-radio-group v-model="batchConfig.style">
                  <el-radio-button label="similar">相似风格</el-radio-button>
                  <el-radio-button label="artistic">艺术风格</el-radio-button>
                  <el-radio-button label="realistic">写实风格</el-radio-button>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="自定义提示">
                <el-input
                  v-model="batchConfig.customPrompt"
                  type="textarea"
                  :rows="3"
                  placeholder="可选：输入自定义提示词..."
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
        
        <template #footer>
          <el-button @click="batchVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBatchGenerate"
            :loading="batchGenerating"
          >
            {{ batchGenerating ? '生成中...' : '开始生成' }}
          </el-button>
        </template>
      </el-dialog>
      
      <!-- 批量生成进度对话框 -->
      <el-dialog
        v-model="batchProgressVisible"
        title="批量扩展进度"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <div class="batch-progress">
          <div class="progress-header">
            <span>正在扩展图片...</span>
            <span>{{ batchProgress.completed }}/{{ batchProgress.total }}</span>
          </div>
          
          <el-progress 
            :percentage="batchProgressPercentage" 
            :status="batchProgress.status"
          />
          
          <div class="progress-details">
            <div class="progress-item" 
                 v-for="item in batchProgress.items" 
                 :key="item.imageId"
                 :class="item.status"
            >
              <el-icon v-if="item.status === 'completed'"><Check /></el-icon>
              <el-icon v-else-if="item.status === 'error'"><Close /></el-icon>
              <el-icon v-else class="loading"><Loading /></el-icon>
              <span>{{ item.imageName }}</span>
              <span class="progress-count">{{ item.generatedCount }}/{{ item.targetCount }}</span>
              <span v-if="item.error" class="error-text">{{ item.error }}</span>
            </div>
          </div>
        </div>
        
        <template #footer>
          <el-button 
            @click="batchProgressVisible = false"
            :disabled="batchProgress.status === 'active'"
          >
            {{ batchProgress.status === 'active' ? '生成中...' : '完成' }}
          </el-button>
        </template>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, DocumentAdd, CopyDocument, MagicStick,
  Check, Close, Loading
} from '@element-plus/icons-vue'
import PageContainer from '@/components/layout/PageContainer.vue'
import ImageSelector from '@/components/generate/ImageSelector.vue'
import ExpansionPanel from '@/components/expand/ExpansionPanel.vue'
import ExpansionResults from '@/components/expand/ExpansionResults.vue'
import { imageApi } from '@/api/image'
import { imageGenerationApi } from '@/api/ai'
import type { 
  ImageModel, 
  GeneratedImageModel, 
  ImageGenerationRequest 
} from '@/types'
import { formatTime, formatFileSize, downloadFile, copyToClipboard } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const images = ref<ImageModel[]>([])
const imagesLoading = ref(false)
const selectedImage = ref<ImageModel | null>(null)
const expandedImages = ref<GeneratedImageModel[]>([])
const generating = ref(false)
const previewVisible = ref(false)
const previewImage = ref<GeneratedImageModel | null>(null)
const expansionPanelRef = ref()

// 批量扩展相关
const batchVisible = ref(false)
const batchImages = ref<ImageModel[]>([])
const batchGenerating = ref(false)
const batchProgressVisible = ref(false)

const batchConfig = reactive({
  count: 2,
  style: 'similar',
  customPrompt: ''
})

const batchProgress = reactive({
  total: 0,
  completed: 0,
  status: 'active' as 'active' | 'success' | 'exception',
  items: [] as Array<{
    imageId: number
    imageName: string
    targetCount: number
    generatedCount: number
    status: 'pending' | 'processing' | 'completed' | 'error'
    error?: string
  }>
})

// 计算属性
const batchProgressPercentage = computed(() => {
  if (batchProgress.total === 0) return 0
  return Math.round((batchProgress.completed / batchProgress.total) * 100)
})

// 方法
const handleLoadImages = async (params: any = {}) => {
  try {
    imagesLoading.value = true
    
    const response = await imageApi.getImages({
      page: 0,
      size: 100,
      sortBy: 'createdAt',
      sortDir: 'desc',
      ...params
    })
    
    if (response.success && response.data) {
      images.value = response.data
    }
  } catch (error) {
    console.error('加载图片失败:', error)
    ElMessage.error('加载图片失败')
  } finally {
    imagesLoading.value = false
  }
}

const handleSelectImage = (image: ImageModel) => {
  selectedImage.value = image
  expandedImages.value = []
  
  if (image) {
    // 加载该图片的扩展历史
    handleLoadHistory(image.id)
  }
}

const handleGenerate = async (config: ImageGenerationRequest) => {
  try {
    generating.value = true
    
    const response = await imageGenerationApi.generateSimilarImages(config)
    
    if (response.success && response.data) {
      expandedImages.value = response.data
      
      // 模拟进度更新
      let current = 0
      const total = config.count
      const interval = setInterval(() => {
        current++
        expansionPanelRef.value?.updateProgress(current, `正在生成第 ${current} 张图片...`)
        
        if (current >= total) {
          clearInterval(interval)
        }
      }, 2000)
      
      ElMessage.success('图片扩展生成成功')
    }
  } catch (error: any) {
    console.error('图片扩展失败:', error)
    ElMessage.error(error.response?.data?.message || '图片扩展失败')
    expansionPanelRef.value?.setError('生成失败，请重试')
  } finally {
    generating.value = false
    expansionPanelRef.value?.setGenerating(false)
  }
}

const handleRegenerate = async (config: ImageGenerationRequest) => {
  await handleGenerate(config)
}

const handleUseHistory = (image: GeneratedImageModel) => {
  expandedImages.value.unshift(image)
}

const handleLoadHistory = async (imageId: number) => {
  try {
    const response = await imageGenerationApi.getImageHistory(imageId)
    if (response.success && response.data) {
      expansionPanelRef.value?.setHistoryImages(response.data)
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

const handlePreview = (image: GeneratedImageModel) => {
  previewImage.value = image
  previewVisible.value = true
}

const handleDownload = (image: GeneratedImageModel) => {
  if (image.generatedImageUrl) {
    downloadFile(image.generatedImageUrl, `扩展图片_${image.id}.jpg`)
    ElMessage.success('开始下载图片')
  }
}

const handleShare = async (image: GeneratedImageModel) => {
  try {
    const shareContent = `AI扩展图片\n原图: ${selectedImage.value?.originalName}\n相似度: ${Math.round((image.similarityScore || 0) * 100)}%\n\n来自AI图文管理系统`
    await copyToClipboard(shareContent)
    ElMessage.success('分享内容已复制到剪贴板')
  } catch (error) {
    ElMessage.error('分享失败')
  }
}

const handleDelete = async (image: GeneratedImageModel, index: number) => {
  try {
    const response = await imageGenerationApi.deleteGeneratedImage(image.id)
    if (response.success) {
      expandedImages.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

const handleUseTemplate = (image: GeneratedImageModel) => {
  // 使用该图片作为新的扩展模板
  ElMessage.info('功能开发中...')
}

const handleGenerateMore = (image: GeneratedImageModel) => {
  // 基于该图片生成更多相似图片
  ElMessage.info('功能开发中...')
}

const handleCompose = (images: GeneratedImageModel[]) => {
  if (images.length === 0) return
  
  router.push({
    name: 'Compose',
    query: {
      imageId: selectedImage.value?.id,
      expandedIds: images.map(img => img.id).join(',')
    }
  })
}

const handleSelectBest = (image: GeneratedImageModel) => {
  // 选择最佳扩展图片的逻辑
}

const downloadPreviewImage = () => {
  if (previewImage.value?.generatedImageUrl) {
    downloadFile(previewImage.value.generatedImageUrl, `扩展图片_${previewImage.value.id}.jpg`)
    ElMessage.success('开始下载图片')
  }
}

const composeWithPreview = () => {
  if (previewImage.value) {
    handleCompose([previewImage.value])
  }
}

const useAsTemplate = () => {
  if (previewImage.value) {
    handleUseTemplate(previewImage.value)
  }
}

const generateMoreFromPreview = () => {
  if (previewImage.value) {
    handleGenerateMore(previewImage.value)
  }
}

const handleCloseBatch = () => {
  batchVisible.value = false
  batchImages.value = []
}

const handleBatchGenerate = async () => {
  if (batchImages.value.length === 0) return
  
  batchGenerating.value = true
  batchProgressVisible.value = true
  batchVisible.value = false
  
  // 初始化进度
  batchProgress.total = batchImages.value.length * batchConfig.count
  batchProgress.completed = 0
  batchProgress.status = 'active'
  batchProgress.items = batchImages.value.map(image => ({
    imageId: image.id,
    imageName: image.originalName,
    targetCount: batchConfig.count,
    generatedCount: 0,
    status: 'pending' as const
  }))
  
  // 逐个处理图片
  for (let i = 0; i < batchImages.value.length; i++) {
    const image = batchImages.value[i]
    const item = batchProgress.items[i]
    
    try {
      item.status = 'processing'
      
      const config: ImageGenerationRequest = {
        originalImageId: image.id,
        count: batchConfig.count,
        style: batchConfig.style,
        customPrompt: batchConfig.customPrompt
      }
      
      const response = await imageGenerationApi.generateSimilarImages(config)
      
      if (response.success && response.data) {
        item.status = 'completed'
        item.generatedCount = response.data.length
        batchProgress.completed += response.data.length
      } else {
        item.status = 'error'
        item.error = '生成失败'
        batchProgress.completed += batchConfig.count
      }
    } catch (error: any) {
      item.status = 'error'
      item.error = error.response?.data?.message || '生成失败'
      batchProgress.completed += batchConfig.count
    }
  }
  
  batchProgress.status = 'success'
  batchGenerating.value = false
  
  const successCount = batchProgress.items.reduce((sum, item) => sum + item.generatedCount, 0)
  ElMessage.success(`批量扩展完成，成功生成 ${successCount} 张图片`)
}

const handleClosePreview = () => {
  previewVisible.value = false
  previewImage.value = null
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'SUCCESS': return '生成成功'
    case 'FAILED': return '生成失败'
    default: return '生成中'
  }
}

const getStyleFromParams = (params: string) => {
  try {
    const config = JSON.parse(params || '{}')
    switch (config.style) {
      case 'similar': return '相似风格'
      case 'artistic': return '艺术风格'
      case 'realistic': return '写实风格'
      case 'cartoon': return '卡通风格'
      case 'vintage': return '复古风格'
      case 'modern': return '现代风格'
      default: return '未知风格'
    }
  } catch {
    return '未知风格'
  }
}

// 生命周期
onMounted(() => {
  // 检查路由参数
  const imageId = route.query.imageId
  const imageIds = route.query.imageIds
  
  if (imageIds) {
    // 批量扩展模式
    const ids = (imageIds as string).split(',').map(id => parseInt(id))
    handleLoadImages().then(() => {
      batchImages.value = images.value.filter(img => ids.includes(img.id))
      if (batchImages.value.length > 0) {
        batchVisible.value = true
      }
    })
  } else if (imageId) {
    // 单个图片模式
    handleLoadImages().then(() => {
      const image = images.value.find(img => img.id === parseInt(imageId as string))
      if (image) {
        handleSelectImage(image)
      }
    })
  } else {
    handleLoadImages()
  }
})
</script>

<style scoped>
.expand-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.expand-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-description {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.expand-content {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 30px;
}

.expand-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: sticky;
  top: 20px;
  height: fit-content;
}

.expand-main {
  min-width: 0;
}

/* 预览对话框样式 */
.preview-content {
  color: #333;
}

.preview-comparison {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-bottom: 30px;
}

.preview-section h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.preview-image-container {
  aspect-ratio: 1;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 20px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.preview-info p {
  margin: 8px 0;
  color: #666;
}

.preview-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 批量扩展样式 */
.batch-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.batch-images h4,
.batch-config h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.batch-images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  gap: 10px;
  max-height: 200px;
  overflow-y: auto;
}

.batch-image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.batch-image-item img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 5px;
}

.batch-image-name {
  font-size: 10px;
  text-align: center;
  color: #666;
  word-break: break-all;
}

/* 批量进度样式 */
.batch-progress {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

.progress-details {
  max-height: 300px;
  overflow-y: auto;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.progress-item.completed {
  color: #67c23a;
}

.progress-item.error {
  color: #f56c6c;
}

.progress-count {
  font-size: 12px;
  color: #666;
}

.error-text {
  font-size: 12px;
  color: #f56c6c;
}

.progress-item .loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .expand-content {
    grid-template-columns: 350px 1fr;
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .expand-page {
    padding: 15px;
  }
  
  .expand-content {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .expand-sidebar {
    position: static;
  }
  
  .preview-comparison {
    grid-template-columns: 1fr;
  }
  
  .preview-actions {
    flex-direction: column;
  }
}
</style>